
var prefix = ctx + "school/paper";

$(function() {
    $("#datetimepicker-startTime").datetimepicker({
        format: 'yyyy-mm-dd',
        minView: "month",
        todayBtn:  true,
        autoclose: true,
        endDate : new Date(),
    }).on('changeDate', function(event) {
        event.preventDefault();
        event.stopPropagation();
        var startTime = event.date;
        $('#datetimepicker-endTime').datetimepicker('setStartDate', startTime);
        $.table.search();
    });

    $("#datetimepicker-endTime").datetimepicker({
        format: 'yyyy-mm-dd',
        minView: "month",
        todayBtn:  true,
        autoclose: true,
        endDate : new Date(),
    }).on('changeDate', function(event) {
        event.preventDefault();
        event.stopPropagation();
        var endTime = event.date;
        $("#datetimepicker-startTime").datetimepicker('setEndDate', endTime);
        $.table.search();
    });
    $('.dual_select').bootstrapDualListbox({
        nonSelectedListLabel: '未添加',
        selectedListLabel: '已添加',
        preserveSelectionOnMove: 'moved',
        moveOnSelect: false,           // 出现一个剪头，表示可以一次选择一个
        filterTextClear: '展示所有',
        moveSelectedLabel: "添加",
        moveAllLabel: '添加所有',
        removeSelectedLabel: "移除",
        removeAllLabel: '移除所有',
        infoText: '',
        infoTextEmpty: '',
        showFilterInputs: false,       // 是否带搜索
        selectorMinimalHeight: 140
    });
    /*$('.question_types').on('click', function (e, clickedIndex, isSelected, previousValue) {
        // 处理自己的业务
        $.table.search();

    });*/
    $('#subject').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        // 处理自己的业务
        $.table.search();
    });
    $('#gradeId').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
        // 处理自己的业务
        $.table.search();
    });

    $(document).on("click", ".question_types", function() {
        $("#type").val($(this).attr('type_value'));
        $('#gradeId').attr("disabled",false);
        $('#subject').attr("disabled",false);
        $.table.search();
        $('#gradeId').attr("disabled",true);
        $('#subject').attr("disabled",true);
    });


})

/**
 * 获取总分数
 */
function getScore() {
    var row=$("#bootstrap-table").bootstrapTable('getSelections');
    var totalScore = 0;
    if(row != null && row.length > 0) {
        for (var i = 0; i < row.length; i++) {
            totalScore = parseInt(totalScore) + parseInt(row[i].score);
        }
    }
    $("#totalScore").val(totalScore);
}

function getQuestionTypes() {
    var typesValue = $('.dual_select').val();

    if(typesValue != null){
        $("#question_types").html('');
        $("#type").val(typesValue[0]);
      //  $("#type").addClass('active');
        var value = '';
        for (let i = 0; i < typesValue.length; i++) {
            var text = '';
            $.each(typeDatas, function(index, dict) {
                if (dict.dictValue == (typesValue[i])) {
                    text = dict.dictLabel;
                    return false;
                }
            });
            var active = '';
            if(i==0){
                var bt = '<li  class="question_types active" type_value="'+typesValue[i]+'" ><a href="#" class="question_types_active">'+text+'</a></li>';
                $("#question_types").append(bt);
            }else {
                var bt = '<li  class="question_types" type_value="'+typesValue[i]+'" ><a href="#">'+text+'</a></li>';
                $("#question_types").append(bt);
            }

            if(value == ''){
                value+=typesValue[i];
            }else {
                value+=','+typesValue[i];
            }
        }
        $("#questionTypesValue").val(value);
        $(".question_types_active").trigger("click");
       /* $('#gradeId').attr("disabled",false);
        $('#subject').attr("disabled",false);
        $.table.search();
        $('#gradeId').attr("disabled",true);
        $('#subject').attr("disabled",true);*/

    }
}

function savePaperInfo(optType){

    //$("#tab-2").show();

    getScore();
    getQuestionTypes();
    $('#gradeId').attr("disabled",false);
    $('#subject').attr("disabled",false);
    if($("#paperId").val() != ''){
        optType = 'edit';
    }else {
        $("#gradeName").val($("#gradeId option:selected").text());
    }

    var data = $('#form-paper-'+optType).serializeJSON();
    if ($.validate.form()) {
        var config = {
            url:  prefix + "/"+optType,
            type: "post",
            dataType: "json",
            data: data,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $("#paperId").val(result.data);
                $.modal.closeLoading();
                $("#question_tab").tab('show');
            }
        };
        $.ajax(config)
    }
    $('#gradeId').attr("disabled",true);
    $('#subject').attr("disabled",true);

}




function  removeQuestion(id,index) {
    if($("#paperId").val() == ""){
        $.modal.alertWarning("请先保存试卷基本信息!");
        return;
    }
    var config = {
        url: prefix + "/updatePaperQuestion?questionId="+id+"&paperId="+$("#paperId").val()+"&type=2",
        type: "get",
        dataType: "json",
        beforeSend: function () {
            $.modal.loading("正在处理中，请稍后...");

        },
        success: function(result) {

            //$.modal.msgSuccess("删除成功");
            $.modal.closeLoading();
            $('#bootstrap-table').bootstrapTable('uncheckBy', {field: 'id', values:[Number(id)]});
            saveQuestionId();
            getScore();
        }
    };
    $.ajax(config)
}

function  addQuestion(id,index) {
    if($("#paperId").val() == ""){
        $.modal.alertWarning("请先保存试卷基本信息!");
        return;
    }
    var config = {
        url: prefix + "/updatePaperQuestion?questionId="+id+"&paperId="+$("#paperId").val()+"&type=1",
        type: "get",
        dataType: "json",
        beforeSend: function () {
            $.modal.loading("正在处理中，请稍后...");

        },
        success: function(result) {

            //$.modal.msgSuccess("添加成功");
            $.modal.closeLoading();
            $('#bootstrap-table').bootstrapTable('checkBy', {field: 'id', values:[Number(id)]});
            saveQuestionId();
            getScore();

        }
    };
    $.ajax(config)
}

function saveQuestionId() {
    var questionListArray = $("#bootstrap-table").bootstrapTable('getSelections');
    if(questionListArray != null){
        var ids = "";
        for (let i = 0; i < questionListArray.length; i++) {
            if(ids == ""){
                ids = questionListArray[i].id;
            }else {
                ids += ","+questionListArray[i].id;
            }
        }
        $("#questionIds").val(ids);
    }
    $('#gradeId').attr("disabled",false);
    $('#subject').attr("disabled",false);
    $.table.search();
    $('#gradeId').attr("disabled",true);
    $('#subject').attr("disabled",true);


}

$(function() {
    var options = {
        url: ctx + "school/question/getQuestionListByCondition",
        detailUrl:ctx + "school/question/detail/{id}",
        removeUrl: prefix + "/remove",
        modalName: "试题",
        showSearch: false,
        showRefresh: false,
        showColumns: false,
        showToggle: false,
        uniqueId : 'id',
        columns: [{
            checkbox: true
        },
            {
                field: 'id',
                title: 'id',
                visible: false
            },
            {
                field: 'name',
                title: '试题名称'
            },
            {
                field: 'content',
                title: '内容',
                formatter: function(value, row, index) {
                    var div = '<div  style="max-width:600px;max-height: 50px; white-space: nowrap;text-overflow:ellipsis;overflow: hidden;">'+value+'</div>';
                    return div;
                }
            },
            {
                field: 'difficulty',
                title: '难度',
                formatter: function(value, row, index) {
                    return $.table.selectDictLabel(difficultyDatas, value);
                }
            },
            {
                field: 'score',
                title: '分数'
            },
            {
                title: '操作',
                field: 'opt',
                align: 'center',
                formatter: function(value, row, index) {
                    var actions = [];
                    actions.push('<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.detail(' + row.id + ')">详情</a> ');
                    actions.push('<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="report(\'' + row.id + '\')"><i class="fa fa-eye"></i>统计</a> ');
                    var questionIds = $("#questionIds").val().split(",");
                    if(questionIds != null && questionIds != ""){


                        var isSelected = false;
                        for (var i = 0 ;i<= questionIds.length;i++){

                            if(row.id == questionIds[i]){

                                actions.push('<a class="btn btn-danger btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="removeQuestion(' + row.id + ',' + index+ ')">移除</a> ');
                                isSelected = true;
                                break;
                            }
                        }
                        if(!isSelected){
                            actions.push('<a class="btn btn-primary btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="addQuestion(' + row.id + ',' + index+ ')">加入</a> ');
                        }
                    }else {

                        actions.push('<a class="btn btn-primary btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="addQuestion(' + row.id + ',' + index+ ')">加入</a> ');
                    }
                    return actions.join('');
                }
            }],
        onLoadSuccess: function (data) {
            var questionIds = [];
            $.each($("#questionIds").val().split(","), function(i, n) {
                questionIds.push(Number(n))
            });
            $('#bootstrap-table').bootstrapTable('checkBy', {field: 'id', values:questionIds});
        }

    };
    $.table.init(options);



});
function report(id) {

    //$.operate.addUrl("answer");
    $.modal.openTab("试题统计" , ctx + "school/question/report/"+id);
}